<template>
    <div class="edu-page-warp">
        <div class="edu-page-title new">
            <span v-if="activeTab ==1" class="active">课程门数</span>
            <span v-else class="active">虚拟课</span>
        </div>
        <div v-if="activeTab == 1" class="bg-white pd-20px" key="tab1">
            <el-row :gutter="4" style="line-height:24px;">
                <el-col :span="1">
                    <i class="el-icon-info float-right secondary-text" style="margin-top:4px;"></i>
                </el-col>
                <el-col :span="23">
                    <span v-for="item in infos" :key="item" class="secondary-text font-size-14">
                        {{item}}
                        <br>
                    </span>
                </el-col>
            </el-row>
            <el-row class="pd-20px">
                <el-col>
                    <el-table :data="rules" stripe size="mini" class="border-top">
                        <el-table-column type="index" label="序号" width="80"></el-table-column>
                        <el-table-column prop="label" label="课程类别" min-width="120"></el-table-column>
                        <el-table-column label="课程模块最多门数" min-width="120">
                            <template slot-scope="props">
                                <span v-show="props.row.limitType == '0'">{{props.row.totalNum}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="课程模块最少门数" min-width="120">
                            <template slot-scope="props">
                                <span v-show="props.row.limitType == '0'">{{props.row.optional}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="学分限制类型" min-width="120">
                            <template slot-scope="props">
                                <span
                                    v-show="props.row.limitType == '1'"
                                >{{props.row.expression ? (props.row.expression === 1 ? "大于等于" : "等于") : ""}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="学分限制" min-width="120">
                            <template slot-scope="props">
                                <span v-show="props.row.limitType == '1'">{{props.row.minCredits}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="150">
                            <template slot-scope="scope">
                                <el-button
                                    type="text"
                                    @click="showCourseLabelBox(scope.row)"
                                >{{$t('message.edit')}}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-row>
                        <el-col>
                            <el-pagination
                                small
                                @size-change="handleSizeChange"
                                @current-change="handlePageNumChange"
                                :current-page="queryRuleForm.pageNum_"
                                :page-sizes="[20,50,100,500,1000]"
                                :page-size="queryRuleForm.pageSize_"
                                layout="total, prev, pager, next"
                                :total="queryRuleForm.total"
                                style="float: right;margin:10px 60px 0 0;"
                            ></el-pagination>
                        </el-col>
                    </el-row>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="22">
                    <div class="empty-box"></div>
                </el-col>
                <el-col :span="2">
                    <el-button type="primary" @click="ok">确定</el-button>
                </el-col>
            </el-row>
        </div>
        <div v-else class="bg-white pd-20px" key="tab2">
            <el-row>
                <el-col>
                    <el-button
                        class="float-right"
                        style="margin-right: 20px;"
                        size="mini"
                        type="primary"
                        @click="addForeignLangRel"
                    >{{$t("message.add")}}</el-button>
                </el-col>
            </el-row>
            <el-row class="pd-20px">
                <el-col>
                    <el-table :data="foreignLangs" stripe size="mini" class="border-top">
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-form label-width="120px" size="mini">
                                    <el-form-item label="第一外语大课号: ">{{scope.row.courseNameB}}</el-form-item>
                                    <el-form-item label="小课号: ">
                                        <el-tag
                                            size="mini"
                                            :type="'info'"
                                            v-for="item in splitStr(scope.row.courseNameS)"
                                            :key="item"
                                            style="margin: 0 8px 4px 0;"
                                        >{{item}}</el-tag>
                                    </el-form-item>
                                    <el-form-item label="最多门数: ">{{scope.row.maxNumber}}</el-form-item>
                                </el-form>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="序号" width="80"></el-table-column>
                        <el-table-column prop="courseNameB" label="第一外语大课号"></el-table-column>
                        <el-table-column label="小课号">
                            <template slot-scope="scope">
                                <span :title="scope.row.courseNameS">{{scope.row.courseNameS}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="maxNumber" label="最多门数" width="80"></el-table-column>
                        <el-table-column label="操作" width="150">
                            <template slot-scope="scope">
                                <el-button
                                    type="text"
                                    @click="editForeignLangRel(scope.row)"
                                >{{$t('message.edit')}}</el-button>
                                <el-button
                                    type="text"
                                    @click="deleteLine(scope.row.id)"
                                >{{$t('message.delete')}}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-row>
                        <el-col>
                            <el-pagination
                                small
                                @size-change="handleSizeChange1"
                                @current-change="handlePageNumChange1"
                                :current-page="queryForeignLangForm.pageNum_"
                                :page-sizes="[20,50,100,500,1000]"
                                :page-size="queryForeignLangForm.pageSize_"
                                layout="total, prev, pager, next"
                                :total="queryForeignLangForm.total"
                                style="float: right;margin:10px 60px 0 0;"
                            ></el-pagination>
                        </el-col>
                    </el-row>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="22">
                    <div class="empty-box"></div>
                </el-col>
                <el-col :span="2">
                    <el-button type="primary" @click="ok">确定</el-button>
                </el-col>
            </el-row>
        </div>

        <el-dialog title="虚拟课" width="40%" :visible.sync="showForeignLangDialog" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <el-form ref="form" :model="form" label-width="110px">
                <el-row :gutter="20">
                    <el-col>
                        <el-form-item label="大课号">
                            <el-select
                                v-model="curForeignLang.complationsId"
                                filterable
                                placeholder="输入大课号名称搜索"
                                size="mini"
                                remote
                                :remote-method="queryElectiveCourses"
                            >
                                <el-option
                                    v-for="item in electiveCourses"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                    <span style="float: left">{{ item.label }}</span>
                                    <span
                                        style="float: right; color: #8492a6; font-size: 13px"
                                    >{{ item.value }}</span>
                                </el-option>
                                <i class="el-icon-search el-input__icon" slot="prefix"></i>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col>
                        <el-form-item label="小课号">
                            <el-select
                                v-model="curForeignLang.singleId"
                                filterable
                                size="mini"
                                remote
                                placeholder="输入小课号名称搜索"
                                :remote-method="queryOptionalCourses"
                                @change="pickOptionalCourse"
                            >
                                <el-option
                                    v-for="item in optionalCourses"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                    <span style="float: left">{{ item.label }}</span>
                                    <span
                                        style="float: right; color: #8492a6; font-size: 13px"
                                    >{{ item.value }}</span>
                                </el-option>
                                <i class="el-icon-search el-input__icon" slot="prefix"></i>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row gutter="20" v-if="items.length>0">
                    <el-col>
                        <div style="margin-left:110px;margin-bottom:10px">
                            <el-tag
                                size="mini"
                                :type="ele.hasOwnProperty('type')?'info':'primary'"
                                closable
                                v-for="ele in items"
                                :key="ele"
                                style="margin:0 15px 10px 0"
                                @close="unpickCourse(ele)"
                            >{{ele.label}}</el-tag>
                        </div>
                    </el-col>
                </el-row>
                <el-row gutter="20">
                    <el-col>
                        <el-form-item label="最多门数">
                            <el-input-number
                                v-model="maxNumber"
                                @change="maxNumberChange"
                                :min="1"
                                :max="items.length"
                            ></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer">
                <el-button
                    @click="showForeignLangDialog = false"
                    size="mini"
                >{{$t('message.cancel')}}</el-button>
                <el-button
                    @click="saveForeignLangs"
                    type="primary"
                    size="mini"
                >{{$t('message.confirm')}}</el-button>
            </div>
        </el-dialog>

        <el-dialog title="规则设置" width="40%" :visible.sync="showCourseLabelDialog" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <el-form ref="form" :model="form" label-width="90px" inline>
                <el-row>
                    <el-col span="1">&nbsp;</el-col>
                    <el-col span="23">
                        <el-form-item prop="label" label="课程类别:">
                            <el-input v-model="curRule.label" disabled style="width:150px"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col span="1">
                        <el-radio v-model="limitType" style="margin-top:8px;" label="0">&nbsp;</el-radio>
                    </el-col>
                    <el-col span="23">
                        <el-form-item prop="optional" label="至少门数:">
                            <el-input-number
                                v-model="curRule.optional"
                                @change="optionalChange"
                                :min="0"
                                :max="100"
                                size="mini"
                                controls-position="right"
                                style="width:150px"
                                :disabled="limitType == '1'"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item prop="totalNum" label="最多门数:">
                            <el-input-number
                                v-model="curRule.totalNum"
                                @change="totalChange"
                                :min="0"
                                :max="100"
                                size="mini"
                                controls-position="right"
                                style="width:150px"
                                :disabled="limitType == '1'"
                            ></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col span="1">
                        <el-radio v-model="limitType" style="margin-top:8px;" label="1">&nbsp;</el-radio>
                    </el-col>
                    <el-col span="23">
                        <el-form-item prop="optional" label="学分限制:">
                            <el-select v-model="curRule.expression" style="width:150px">
                                <el-option
                                    v-for="item in expressions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    :disabled="limitType == '0'"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="totalNum">
                            <el-input
                                v-model="curRule.minCredits"
                                style="width:60px"
                                :disabled="limitType == '0'"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer">
                <el-button
                    @click="showCourseLabelDialog = false"
                    size="mini"
                >{{$t('message.cancel')}}</el-button>
                <el-button
                    @click="saveCourseRule"
                    type="primary"
                    size="mini"
                >{{$t('message.confirm')}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {
    findCultureRuleList,
    queryCoursesLabelListBytemplateId,
    findComplationsContrastList,
    queryOptionalCourseList,
    queryElectiveCourseList,
    deleteComplationsContrast,
    deleteCultureRule,
    addCultureRule,
    updateCultureRule,
    addComplationsContrast,
    updateComplationsContrast
} from "common/src/api/culture/cultureSchemeRule";

export default {
    name: "CultureSchemeRule",
    data() {
        return {
            activeTab: "tab1",
            infos: [
                "1、选修2学分创新创业的通识选修课程",
                "2、每个模块最多选修两门课程(通识选修课分为人文经典与审美素养、工程能力与创新思维、社会发展与国际视野、科学探索与生命关怀四大模块)",
                "3、至少选修一门精品类通识选修课(核心通识课程、同济烙印课程、长青系列课程、交叉融通课程、校级精品通识课程将用课程标签予以标注)"
            ],
            rules: [],
            tempCourse: { labelId: "", totalNum: "1", optional: "1" },
            foreignLangs: [],
            curRule: {},
            courseLabels: [],
            curForeignLang: {},
            totalLang:[],
            optionalCourses: [],
            electiveCourses: [],
            showForeignLangDialog: false,
            maxNumber:1,
            items: [],
            queryRuleForm: {
                pageSize_: 20,
                pageNum_: 1,
                total: 0,
                taringingId: this.$route.query.id
            },
            queryForeignLangForm: {
                pageSize_: 20,
                pageNum_: 1,
                total: 0,
                templateId: this.$route.query.id
            },
            showCourseLabelDialog: false,
            expressions: [
                { label: "大于等于", value: 1 },
                { label: "等于", value: 2 }
            ],
            limitType: ""
        };
    },
    created() {
        //this.toggle();
        this.activeTab = this.$route.query.projId;
        if(this.activeTab == 1){
            this.queryRules();
        }else{
            this.queryForeignLangs();
        }
    },
    methods: {
        showCourseLabelBox(row) {
            this.curRule = Object.assign({}, row);
            this.limitType = String(row.limitType ? row.limitType : "0");
            this.showCourseLabelDialog = true;
        },
        // toggle(key) {
        //     if (key) this.activeTab = key;
        //     if (this.activeTab == "tab1") this.queryRules();
        //     else this.queryForeignLangs();
        // },
        handleSizeChange(val) {
            this.queryRuleForm.pageSize_ = val;
            this.queryRules();
        },
        handlePageNumChange(val) {
            this.queryRuleForm.pageNum_ = val;
            this.queryRules();
        },
        handleSizeChange1(val) {
            this.queryForeignLangForm.pageSize_ = val;
            this.queryForeignLangs();
        },
        handlePageNumChange1(val) {
            this.queryForeignLangForm.pageNum_ = val;
            this.queryForeignLangs();
        },
        splitStr(s) {
            return s.split(",");
        },
        unpickCourse(tag) {
            this.items = this.items.filter(ele => {
                return ele.value != tag.value;
            });
        },
        pickOptionalCourse(val) {
            this.totalLang.push(val)
            this.totalLang = Array.from(new Set(this.totalLang))

            let temp = this.optionalCourses.filter(item => {
                return item.value == val;
            });
            let isRepeat = this.items.some(item => {
                return item.value == val;
            });
            if (temp.length == 1 && !isRepeat) this.items.push(temp[0]);
            this.curForeignLang.singleId = "";
        },
        addForeignLangRel() {
            this.showForeignLangDialog = true;
            this.maxNumber = 1;
        },
        editForeignLangRel(curRow) {
            this.curForeignLang = Object.assign({}, curRow);
            this.curForeignLang.templateId = this.$route.query.id;
            //console.log(curRow)
            //let query = curRow.courseNameB.replace(/^([\d]*)/, "");
            //this.curForeignLang.complationsId = curRow.courseNameB.replace(/^([\d]*)/, "");
            let query = curRow.courseNameB.charAt(0)
            this.queryElectiveCourses(query);

            if (curRow && curRow.courseNameS && curRow.courseId) {
                let courseIds = curRow.courseId.split(",");
                this.items = curRow.courseNameS.split(",").map((item, i) => {
                    return { label: item, type: 1, value: courseIds[i] };
                });
            }
            this.maxNumber = this.curForeignLang.maxNumber
            this.showForeignLangDialog = true;
        },
        queryOptionalCourses(code) {
            let complationsId = this.curForeignLang.complationsId;
            if (!complationsId) {
                this.$message({
                    type: "warning",
                    message: "请先选择第一外语大课号"
                });
                return;
            }
            let query = {
                code: code,
                complationsId: complationsId
            };
            queryOptionalCourseList(query).then(res => {
                if (res.code == 200) {
                    let temp = this.trans(res.data);
                    this.optionalCourses = temp;
                    // this.optionalCourses = temp.filter(ele => {
                    //     return (
                    //         ele.label
                    //             .toLowerCase()
                    //             .indexOf(code.toLowerCase()) > -1
                    //     );
                    // });
                } else {
                    this.optionalCourses = this.trans(res.data.list);
                    throw res.code;
                }
            });
        },
        queryElectiveCourses(code) {
            if (code == undefined || code == null || code == "") {
                return;
            }
            let templateId = this.$route.query.id;
            let query = { code: code, templateId: templateId };
            queryElectiveCourseList(query).then(res => {
                if (res.code == 200) {
                    let temp = this.trans(res.data);
                    this.electiveCourses = temp;
                    // this.electiveCourses = temp.filter(ele => {
                    //     return (
                    //         ele.label
                    //             .toLowerCase()
                    //             .indexOf(code.toLowerCase()) > -1
                    //     );
                    // });
                } else {
                    this.electiveCourses = [];
                    throw res.code;
                }
            });
        },
        trans(list) {
            return list.map((ele, i, arr) => {
                return { value: ele.code, label: ele.name };
            });
        },
        saveForeignLangs() {
            let foreignLang = this.curForeignLang;
            foreignLang.maxNumber = this.maxNumber;
            let that = this;
            let courseIds = this.items.map(item => {
                return item.value;
            });
            foreignLang.courseId = courseIds.sort().join(",");
            if (!checkForeignLang(foreignLang)) {
                this.$message({ type: "warning", message: "请完善数据" });
                return;
            }
            if (this.maxNumber > this.items.length) {
                this.$message({
                    type: "warning",
                    message: "最多门数不能大于小课号的个数"
                });
                return;
            }
            if (foreignLang.id) this.updateComplationsContrast(foreignLang);
            else this.addComplationsContrast(foreignLang);
            function checkForeignLang(foreignLang) {
                if (foreignLang.complationsId && that.items.length > 0)
                    return true;
                else return false;
            }
        },
        updateComplationsContrast(foreignLang) {
            updateComplationsContrast(foreignLang)
                .then(res => {
                    if (res.code == 200) {
                        this.$message({ type: "success", message: "更新成功" });
                        this.queryForeignLangs();
                    } else throw res.code;
                })
                .catch(err => {
                    this.$message({ type: "error", message: "更新失败" });
                });
        },
        addComplationsContrast(foreignLang) {
            foreignLang.templateId = this.$route.query.id;
            addComplationsContrast(foreignLang)
                .then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: "success",
                            message: "新增大小课对照规则成功"
                        });
                        this.queryForeignLangs();
                    } else throw res.code;
                })
                .catch(err => {
                    this.$message({
                        type: "error",
                        message: "新增大小课对照规则失败"
                    });
                });
        },
        labelSelect(val) {
            this.curRule.labelId = val.labelId;
        },
        totalChange(val) {
            this.curRule.totalNum = val;
        },
        optionalChange(val) {
            this.curRule.optional = val;
        },
        saveCourseRule() {
            let rule = this.curRule;
            if (rule.optional - rule.totalNum > 0) {
                return this.$message({
                    type: "error",
                    message: "至少门数不能多余最多门数!"
                });
            }
            rule.limitType = this.limitType;
            if (!checkRule(rule)) {
                this.$message({ type: "error", message: "请完善数据" });
                return;
            }
            this.updateCultureRule(rule);
            function checkRule(rule) {
                if (rule.id) return true;
                else return false;
            }
        },
        updateCultureRule(rule) {
            updateCultureRule(rule)
                .then(res => {
                    if (res.code == 200) {
                        this.$message({ type: "success", message: "更新成功" });
                        this.queryRules();
                        this.showCourseLabelDialog = false;
                    } else throw res.code;
                })
                .catch(err => {
                    console.log(err);
                    this.$message({ type: "error", message: "更新失败" });
                });
        },
        queryRules() {
            findCultureRuleList(this.queryRuleForm)
                .then(res => {
                    if (res.code == 200) {
                        this.rules = res.data.list;
                        this.queryRuleForm.total = res.data.total_;
                        this.curRule = {};
                    } else throw res.code;
                })
                .catch(err => {
                    console.log(err);
                });
        },
        queryForeignLangs() {
            if(!this.queryForeignLangForm.templateId){
                return
            }
            findComplationsContrastList(this.queryForeignLangForm).then(res => {
                if (res.code == 200) {
                    this.foreignLangs = res.data.list;
                    this.queryForeignLangForm.total = res.data.total_;
                    this.curForeignLang = {};
                    this.showForeignLangDialog = false;
                } else throw res.code;
            });
        },
        deleteLine(id) {
            if (!id) return;
            this.$confirm("将删除该行数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                if (this.activeTab == 1) this.deleteCultureRule(id);
                else this.deleForeignLang(id);
            });
        },
        deleteCultureRule(id) {
            deleteCultureRule({ id: id })
                .then(res => {
                    if (res.code == 200)
                        this.$message({
                            type: "success",
                            message: "删除成功"
                        });
                    else throw res.code;
                    this.curRule = {};
                    this.queryRules();
                })
                .catch(err => {
                    this.$message({
                        type: "error",
                        message: "删除失败"
                    });
                });
        },
        deleForeignLang(id) {
            deleteComplationsContrast({ id: id })
                .then(res => {
                    if (res.code == 200)
                        this.$message({
                            type: "success",
                            message: "删除成功"
                        });
                    else throw res.code;
                    this.curForeignLang = {};
                    this.queryForeignLangs();
                })
                .catch(err => {
                    this.$message({
                        type: "error",
                        message: "删除失败"
                    });
                });
        },
        ok(){
            this.$store.commit("delete_tabs", this.$route.path);
            this.$router.back();
        }
    },
    watch: {
        activeTab: function(_new, _old) {},
        showForeignLangDialog: function(_new, _old) {
            if (!_new) {
                this.maxNumber = 1;
                this.items = [];
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.new.edu-page-title {
    margin-bottom: 0;
    span {
        cursor: pointer;
        display: inline-block;
        padding-right: 20px;
    }
    span.active {
        padding: 8px 15px;
        color: #66b1ff;
        background: #fff;
        font-weight: 500;
        font-size: 16px;

    }
}

</style>

